package com.wang.mvchain.job;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.Callable;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.wang.mvchain.common.util.ConstatFinalUtil;
import com.wang.mvchain.common.util.ExecutorServiceUtil;
import com.wang.mvchain.common.util.HtmlParserUtil;
import com.wang.mvchain.finan.service.IFinanService;
import com.wang.mvchain.outer.IOutTimerService;
import com.wang.mvchain.stat.pojo.AStatTask;
import com.wang.mvchain.stat.service.IStatService;
import com.wang.mvchain.system.pojo.ACoinrate;
import com.wang.mvchain.system.pojo.ACoinrateEnum;
import com.wang.mvchain.system.pojo.ASyspro;
import com.wang.mvchain.system.pojo.ASysproEnum;
import com.wang.mvchain.system.pojo.ATradeType;
import com.wang.mvchain.system.service.ISystemService;
import com.wang.mvchain.system.service.IWebsiteService;
import com.wang.mvchain.util.ServiceCallableUtil;

/**
 * Spring自带的job
 * 
 * @author wangsh
 */

@Service("jobService")
public class JobService
{
	@Resource
	private IOutTimerService outTimerService;
	@Resource
	private IWebsiteService websiteService;
	@Resource
	private IStatService statService ; 
	@Resource
	private ISystemService systemService;
	@Resource
	private IFinanService finanService ;
	
	private boolean exeFlag = true ; 
	
	/**
	 * 初始化资源
	 */
	@PostConstruct
	private void initMethod()
	{
		ConstatFinalUtil.SYS_LOG.info("----初始化所有抓取行情的线程开始----");
		this.outTimerService.startDeptService();
		ConstatFinalUtil.SYS_LOG.info("----初始化所有抓取行情的线程结束----");
		
		//重新加载配置
		this.sysproReload();
	}

	/**
	 * btc mv chain
	 */
	public void coinMvchain()
	{
		ConstatFinalUtil.TIMER_LOG.info("----- 创建抓取(coinMvchain)任务开始 -----");
		try
		{
			if(exeFlag)
			{
				exeFlag = false ; 
				
				/* 对数据库做一些重置 */
				this.dbReset();
				
				//查询一下所有搬砖的币种
				Map<String, Object> condMap = new HashMap<String, Object>();
				condMap.put("status", ACoinrateEnum.STATUS_ENABLE.getStatus());
				condMap.put("prostatus", ACoinrateEnum.PROSTATUS_ENABLE.getStatus());
				List<ACoinrate> coinrateList = this.websiteService.findCondListCoinrateService(null, condMap);
				
				//搬砖的币种
				List<Callable<Object>> callList = new ArrayList<Callable<Object>>();
				for (Iterator iterator = coinrateList.iterator(); iterator.hasNext();)
				{
					ACoinrate coinrate = (ACoinrate) iterator.next();
					if(coinrate.getId() == ConstatFinalUtil.CONFIG_JSON.getIntValue("USD_ID"))
					{
						/* 美元不搬砖 */
						continue ;
					}
					//买单
					Map<String, Object> threadMap = new HashMap<String, Object>();
					threadMap.put("coinrate", coinrate);
					
					ServiceCallableUtil mvchainThreadUtil = new ServiceCallableUtil();
					mvchainThreadUtil.setParamsMap(threadMap);
					mvchainThreadUtil.setOutTimerService(this.outTimerService);
					mvchainThreadUtil.setOperType("mvchain");
					callList.add(mvchainThreadUtil);
				}
				
				/* 调用所有的线程,要等待 */
				ExecutorServiceUtil.invokeAll(callList);
				
				//处理挂单,计算收益
				this.outTimerService.operTaskExecuteService("first");
				
				/* 交易 */
				/*this.outTimerService.operTaskTradeService();*/
				
				//处理挂单,计算收益
				this.outTimerService.operTaskExecuteService("second");
				
				//抓取汇率,汇率不用抓取了.直接现算
				/*this.coinrate();*/
				//计算每天统计任务
				this.updateStatTaskService(); 
				
				//重新加载配置
				this.sysproReload();
				exeFlag = true ; 
			}else
			{
				ConstatFinalUtil.TIMER_LOG.info("----- 创建抓取(coinMvchain) 上次任务木有执行完成 -----");
			}
		} catch (Exception e)
		{
			ConstatFinalUtil.TIMER_LOG.error("coinMvchain报错了;" , e);
		}finally
		{
			exeFlag = true ; 
		}
		ConstatFinalUtil.TIMER_LOG.info("----- 创建抓取(coinMvchain)任务结束 -----");
	}

	/**
	 * 更新汇率
	 * 每天0点抓取一次
	 */
	public void coinrate()
	{
		ConstatFinalUtil.TIMER_LOG.info("----- 抓取汇率开始 -----");
		Calendar now = Calendar.getInstance();
		//一天执行一次
		if (now.get(Calendar.MINUTE) == 0 && now.get(Calendar.SECOND) < 10)
		{
			// 接着往下执行
		} else
		{
			// 不执行
			return;
		}
		
		Map<String, Object> condMap = new HashMap<String, Object>();
		// 更新汇率
		HtmlParserUtil htmlParserUtil = new HtmlParserUtil();
		JSONObject condJSON = new JSONObject();
		JSONObject resultJSON = htmlParserUtil.findCoinrateRate(condJSON);
		// 查询货币
		for (Iterator iterator = resultJSON.entrySet().iterator(); iterator
				.hasNext();)
		{
			Entry me = (Entry) iterator.next();
			String key = me.getKey() + "";
			JSONObject valJSON = (JSONObject) me.getValue();
			// 查询币种
			String from = valJSON.get("from") + "";
			String rate = valJSON.get("rate") + "";

			condMap.clear();
			condMap.put("engname", from);
			ACoinrate coinrate = this.websiteService.findOneCoinrateService(condMap);
			if (coinrate != null)
			{
				// 更新fromcoinid为coinrate的汇率
				ATradeType tradeType = new ATradeType();
				tradeType.setTocoinid(coinrate.getId());
				tradeType.setRate(Double.valueOf(rate));
				tradeType.setUpdatetime(new Date());
				//汇率大于0时才起作用
				if(tradeType.getRate() > 0 )
				{
					//更新汇率
					JSONObject resultdbJSON = this.websiteService.updateBatchTradeTypeService("updateRate",tradeType);
					ConstatFinalUtil.TIMER_LOG.info("----执行结果----" + resultdbJSON);
				}else
				{
					ConstatFinalUtil.TIMER_LOG.info("----获取汇率有问题:----" + valJSON);
				}
			}
		}
		ConstatFinalUtil.TIMER_LOG.info("----- 抓取汇率结束 -----");
	}
	
	/**
	 * 计算每天统计任务
	 */
	public void updateStatTaskService()
	{
		ConstatFinalUtil.TIMER_LOG.info("----- 计算每天统计任务开始 -----");
		Calendar now = Calendar.getInstance();
		//一天执行一次
		if (now.get(Calendar.HOUR_OF_DAY) == 0 && now.get(Calendar.MINUTE) == 0
				&& now.get(Calendar.SECOND) < 3)
		{
			// 接着往下执行
		} else
		{
			// 不执行
			return;
		}
		//任务统计
		now.add(Calendar.DATE, -1);
		AStatTask statTask = this.statService.updateStatTaskService(now.getTime());
		if(statTask != null && "1".equalsIgnoreCase(ConstatFinalUtil.SYSPRO_MAP.get("multi.users")))
		{
			/* 为任务计算收益 */
			this.finanService.operAssetPriftService(statTask);
		}
		ConstatFinalUtil.TIMER_LOG.info("----- 计算每天统计任务结束 -----");
	}
	
	/**
	 * 数据库做一些重置
	 */
	public void dbReset()
	{
		ConstatFinalUtil.TIMER_LOG.info("----- 数据库重置开始 -----");
		Calendar now = Calendar.getInstance();
		//一天执行一次
		if (now.get(Calendar.HOUR_OF_DAY) == 0 && now.get(Calendar.MINUTE) == 0 && now.get(Calendar.SECOND) < 1)
		{
			// 接着往下执行
		} else
		{
			// 不执行
			return;
		}
		
		Map<String,Object> condMap = new HashMap<String,Object>();
		condMap.clear();
		condMap.put("operType","todayprift");
		int res = this.finanService.operAssetBatchService(condMap);
		ConstatFinalUtil.TIMER_LOG.info("----- 用户资产的今日收益清0--影响条数:{}",res);
		/*condMap.clear();
		this.finanService.operAssetPercentSyncService();
		ConstatFinalUtil.TIMER_LOG.info("----- 重新计算百分比 -----");*/
		ConstatFinalUtil.TIMER_LOG.info("----- 数据库重置结束 -----");
	}
	
	/**
	 * 重新加载配置
	 */
	public void sysproReload()
	{
		Map<String, Object> condMap = new HashMap<String,Object>();
		//加载系统配置
		condMap.clear();
		condMap.put("status", ASysproEnum.STATUS_ENABLE.getStatus());
		condMap.put("reload", "reload");
		List<ASyspro> sysproList = this.systemService.findCondListSysproService(null, condMap);
		ConstatFinalUtil.SYS_LOG.info("初始化系统配置完成:总条数:{},详情:{}",
				ConstatFinalUtil.SYSPRO_MAP.size() , ConstatFinalUtil.SYSPRO_MAP);
	}
}
